//面试题 16.06.最小差
//https://leetcode.cn/problems/smallest-difference-lcci/
class Solution {
public:
    int smallestDifference(vector<int>& a, vector<int>& b) {
        //永远保持两指针数的差值最小 两数最接近
        sort(a.begin(),a.end());
        sort(b.begin(),b.end());
        int na = a.size();
        int nb = b.size();
        long long ret = LLONG_MAX;

        int pa = 0,pb = 0;
        while(pa < na && pb < nb)
        {
            //使用long long防止溢出 和INT_MIN和INT_MAX的问题
            long long numa = a[pa],numb = b[pb];
            ret = min(abs(numa-numb),ret);

            if(numa < numb) ++pa;
            else if(numa > numb) ++pb;
            else return 0; //两个相等的数
        }
        return ret;
    }
};